'''
Created on Jul 22, 2009

@author: sternron
'''
import cliques.mdp.heuristicMdp
from cliques.mdp.potentialBasedState import potentialBasedState

class ldfsState(potentialBasedState):
    def __init__(self,pcdb,g):
        potentialBasedState.__init__(pcdb, g)
        self.solved = False

class ldfs(cliques.mdp.heuristicMdp.heuristicMdp):
    '''
    classdocs
    '''

    def __init__(self,k,edge_prob, num_of_nodes):
        '''
        Constructor
        '''
        cliques.mdp.heuristicMdp.heuristicMdp.__init__(self, k, edge_prob, num_of_nodes)

    def create_state_0(self, ckg, generated):
        return ldfsState(potentialCliques(self.k, self.search.pcdb),\
                             len(ckg) - len(generated))

    def is_action(self,state):
        return isinstance(state,tuple)

    def is_terminal(self,state):
        if len(state.actions())==0:
            return True
        else:
            return False

    def iterate(self, state):
        if self.is_goal(state) or self.is_terminal(state):
            if self.is_terminal(state):
                self.v[state]=state.g
            state.solved = True
            return True
        is_solved = False 
        best_action = None
        for action in state.actions():
            is_solved = True
            if self.q(state,action)>v[state]:
                continue
            for (new_state, state_prob) in self.generate_next_states(state, action):
                is_solved = is_solved and self.iterate(new_state)
            if is_solved:
                best_action = action
                break; # I don't understand this line
        if is_solved:
            self.policy[state]=best_action
            state.solved = True
        else:
            min_value=100000
            for action in state.actions():
                value = self.q(state,action)
                if value<min_value:
                    min_value = value
            self.v[state]=min_value
        
        return is_solved
            
    def run(self, ckg,generated):
        self.v = dict()
        self.policy = dict()
        state_0 = self.create_state_0(ckg, generated)        
        solved = self.iterate(state_0)
        while solved==False:
            solved = self.iterate(state_0)
        if solved==True:
            return (self.v[state_0], self.policy[state_0])    


